import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, Button, Input } from '@/components';
import { Tabs, message, Table, Space, Popconfirm, Tree, Select, Dropdown, Menu, DatePicker, Radio, Checkbox, Tag, Modal } from 'antd';
import { FileText, Folder, Plus,  FolderPlus, Edit2, Move, Search, MoreHorizontal, Download, Star, StarOff, Copy, Grid, Upload as UploadIcon, Trash2, Share2, Filter } from 'lucide-react';
import { useTranslation } from '@/utils/i18n';
import { useThemeStore } from '@/stores/themeStore';
import { documentAPI, DocumentNode, CreateDocumentParams, UpdateDocumentParams, ShareConfig } from '@/utils/api';
import type { TableProps } from 'antd';

const DocumentList: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const themeStore = useThemeStore();
  const isDark = themeStore.getEffectiveTheme() === 'dark';
  const [activeTab, setActiveTab] = useState<'documents' | 'favorites'>('documents');
  const [documents, setDocuments] = useState<DocumentNode[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedFolderId, setSelectedFolderId] = useState<string | null>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showCreateFolderModal, setShowCreateFolderModal] = useState(false);
  const [newDocName, setNewDocName] = useState('');
  const [newFolderName, setNewFolderName] = useState('');
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [viewMode, setViewMode] = useState<'tree' | 'list' | 'grid'>('tree');
  const [keyword, setKeyword] = useState('');
  const [treeKeyword, setTreeKeyword] = useState('');
  const [sortKey, setSortKey] = useState<'updatedAt' | 'name' | 'type' | 'author' | 'size'>('updatedAt');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [creatingDoc, setCreatingDoc] = useState(false);
  const [creatingFolder, setCreatingFolder] = useState(false);
  const [showRenameModal, setShowRenameModal] = useState(false);
  const [renamingItem, setRenamingItem] = useState<DocumentNode | null>(null);
  const [newName, setNewName] = useState('');
  const [showMoveModal, setShowMoveModal] = useState(false);
  const [movingItem, setMovingItem] = useState<DocumentNode | null>(null);
  const [batchMovingTarget, setBatchMovingTarget] = useState<string | null>(null);
  const [showBatchMoveModal, setShowBatchMoveModal] = useState<boolean>(false);
  const [showBatchExportModal, setShowBatchExportModal] = useState<boolean>(false);
  const [showBatchCopyModal, setShowBatchCopyModal] = useState<boolean>(false);
  const [showBatchRenameModal, setShowBatchRenameModal] = useState<boolean>(false);
  const [showBatchTagModal, setShowBatchTagModal] = useState<boolean>(false);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [showFavoritesTab, setShowFavoritesTab] = useState<boolean>(true);
  const [targetFolderId, setTargetFolderId] = useState<string | null>(null);
  const [renameLoading, setRenameLoading] = useState(false);
  const [moveLoading, setMoveLoading] = useState(false);
  const [copyLoading, setCopyLoading] = useState(false);
  const [batchCopyTarget, setBatchCopyTarget] = useState<string | null>(null);
  const [batchRenamePrefix, setBatchRenamePrefix] = useState('');
  const [batchRenameStartNumber, setBatchRenameStartNumber] = useState(1);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [batchTags, setBatchTags] = useState<string[]>([]);
  const [allTags, setAllTags] = useState<Array<{ id: string; name: string }>>([]);
  const [batchSelectedTags, setBatchSelectedTags] = useState<string[]>([]);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [selectedDocumentForMenu, setSelectedDocumentForMenu] = useState<DocumentNode | null>(null);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any
  const contextMenuRef = useRef<any>(null);
  const [showAdvancedSearch, setShowAdvancedSearch] = useState(false);
  const [advancedSearchParams, setAdvancedSearchParams] = useState<{
    author: string;
    startDate: Date | null;
    endDate: Date | null;
    minSize: number;
    maxSize: number;
    isFavorite: boolean;
  }>({
    author: '',
    startDate: null,
    endDate: null,
    minSize: 0,
    maxSize: 100,
    isFavorite: false
  });
  const [showShareModal, setShowShareModal] = useState(false);
  const [sharingItem, setSharingItem] = useState<DocumentNode | null>(null);
  const [shareConfig, setShareConfig] = useState<ShareConfig>({
    expireDays: 7,
    password: '',
    downloadLimit: 100,
    permissions: 'view'
  });
  const [showUploadModal, setShowUploadModal] = useState(false);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [isDragging, setIsDragging] = useState(false);
  const [draggedItem, setDraggedItem] = useState<DocumentNode | null>(null);
  const [draggedOverItem, setDraggedOverItem] = useState<string | null>(null);
  const [fileList, setFileList] = useState<Array<{uid: string; name: string; status: 'ready' | 'uploading' | 'done' | 'error'; originFileObj?: File}>>([]);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [searchHighlight, setSearchHighlight] = useState(false);

  const tableThemeClassName = isDark ? 'document-table-dark' : 'document-table-light';
  const tableHeaderClassName = isDark ? 'bg-slate-900/80 text-slate-100' : 'bg-slate-200 text-slate-700';
  const tableRowClassName = (_: DocumentNode, index: number) =>
    `${isDark ? (index % 2 === 0 ? 'bg-slate-800/60 text-slate-100' : 'bg-slate-800/40 text-slate-100') : index % 2 === 0 ? 'bg-white' : 'bg-slate-50'} transition-colors ${isDark ? 'hover:bg-blue-400/15' : 'hover:bg-blue-500/10'}`;
  const tableStyle: React.CSSProperties = isDark
    ? { backgroundColor: 'rgba(15, 23, 42, 0.75)' }
    : { backgroundColor: '#f8fafc' };
  const tableThemeProps: Partial<TableProps<DocumentNode>> = {
    className: `rounded-xl overflow-hidden border ${isDark ? 'border-slate-700 bg-slate-800/60' : 'border-gray-200 bg-white'} ${tableThemeClassName}`,
    rowClassName: tableRowClassName,
    onHeaderRow: () => ({
      className: `transition-colors ${tableHeaderClassName}`,
    }),
    style: tableStyle,
  };

  // 生成同父级下不重复的名称
  const generateUniqueName = useCallback((base: string) => {
    const siblings = documents.filter(d => d.parentId === selectedFolderId).map(d => d.name);
    if (!siblings.includes(base)) return base;
    let idx = 2;
    let candidate = `${base}(${idx})`;
    while (siblings.includes(candidate)) {
      idx += 1;
      candidate = `${base}(${idx})`;
    }
    return candidate;
  }, [documents, selectedFolderId]);

  // 将文档列表转换为树形结构
  const buildTree = useCallback((docs: DocumentNode[], parentId: string | null = null): DocumentNode[] => {
    return docs
      .filter(doc => doc.parentId === parentId)
      .map(doc => ({
        ...doc,
        // 确保名称不为空，与表格视图保持一致
        name: (doc.name && doc.name.trim()) ? doc.name : '未命名',
        children: doc.type === 'folder' ? buildTree(docs, doc.id) : undefined
      }));
  }, []);

  // 规范化与去重（防止后端偶发返回空名称或重复项导致"空白一行"）
  // 递归处理所有层级的文档和文件夹
  const normalizeDocuments = useCallback((docs: DocumentNode[]): DocumentNode[] => {
    if (!Array.isArray(docs)) {
      console.warn('normalizeDocuments: 输入不是数组', docs);
      return [];
    }
    const seen = new Set<string>();
    const normalizeDoc = (doc: DocumentNode): DocumentNode | null => {
      if (!doc || !doc.id) return null;
      if (seen.has(doc.id)) return null;
      seen.add(doc.id);
      
      return {
        ...doc,
        // 规范化文档名称
        name: (doc.name && doc.name.trim()) ? doc.name : '未命名',
        // 递归处理子文档
        children: doc.children && Array.isArray(doc.children) 
          ? doc.children
              .map(normalizeDoc)
              .filter((child): child is DocumentNode => child !== null)
          : undefined
      };
    };
    
    // 处理顶级文档并过滤掉null值
    const result = docs
      .map(normalizeDoc)
      .filter((doc): doc is DocumentNode => doc !== null);
    console.log('normalizeDocuments: 输入', docs.length, '项，输出', result.length, '项');
    return result;
  }, []);

  // 重命名文档/文件夹
  const handleRename = async () => {
    if (renameLoading || !renamingItem || !newName.trim()) return;
    
    try {
      setRenameLoading(true);
      const params: UpdateDocumentParams = {
        name: newName.trim()
      };
      await documentAPI.updateDocument(renamingItem.id, params);
      message.success('重命名成功');
      setShowRenameModal(false);
      setRenamingItem(null);
      setNewName('');
      loadDocuments();
    } catch (error) {
      console.error('重命名失败:', error);
      message.error('重命名失败');
    } finally {
      setRenameLoading(false);
    }
  };

  // 移动文档/文件夹
  const handleMove = async () => {
    if (moveLoading || !movingItem || targetFolderId === undefined) return;
    
    // 检查是否移动到自身或子文件夹中
    if (targetFolderId === movingItem.id) {
      message.warning('不能移动到自身');
      return;
    }
    
    // 检查是否移动到子文件夹中
    const isChildFolder = (folderId: string, targetId: string): boolean => {
      const folder = documents.find(d => d.id === folderId);
      if (!folder || folder.type !== 'folder' || !folder.children) return false;
      if (folder.children.some(child => child.id === targetId)) return true;
      return folder.children.some(child => child.type === 'folder' && isChildFolder(child.id, targetId));
    };
    
    if (movingItem.type === 'folder' && isChildFolder(targetFolderId, movingItem.id)) {
      message.warning('不能移动到子文件夹中');
      return;
    }
    
    try {
      setMoveLoading(true);
      await documentAPI.moveDocument(movingItem.id, targetFolderId);
      message.success('移动成功');
      setShowMoveModal(false);
      setMovingItem(null);
      setTargetFolderId(null);
      loadDocuments();
    } catch (error) {
      console.error('移动失败:', error);
      message.error('移动失败');
    } finally {
      setMoveLoading(false);
    }
  };

  // 准备重命名
  const prepareRename = (item: DocumentNode) => {
    setRenamingItem(item);
    setNewName(item.name);
    setShowRenameModal(true);
  };

  // 准备移动
  const prepareMove = (item: DocumentNode) => {
    setMovingItem(item);
    setTargetFolderId(null);
    setShowMoveModal(true);
  };

  // 构建文件夹选择树（排除自身和子文件夹）
  const buildFolderTreeForSelection = (docs: DocumentNode[], excludeId?: string, parentId: string | null = null): Array<{value: string | null; label: string; isLeaf?: boolean; children?: Array<{value: string | null; label: string; isLeaf?: boolean}>}> => {
    const result = [];
    
    // 添加根目录选项
    if (parentId === null && (!excludeId || excludeId !== 'root')) {
      result.push({ value: null, label: '根目录' });
    }
    
    const folders = docs.filter(doc => 
      doc.type === 'folder' && 
      doc.parentId === parentId && 
      doc.id !== excludeId &&
      // 排除子文件夹（防止循环引用）
      (!excludeId || !isChildFolder(excludeId, doc.id))
    );
    
    for (const folder of folders) {
      const item = {
        value: folder.id,
        label: folder.name
      };
      
      const children = buildFolderTreeForSelection(docs, excludeId, folder.id);
      if (children.length > 0) {
        item['children'] = children;
      }
      
      result.push(item);
    }
    
    return result;
  };
  
  // 检查是否是子文件夹
  const isChildFolder = (parentId: string, folderId: string): boolean => {
    const folder = documents.find(d => d.id === folderId);
    if (!folder) return false;
    
    let current: DocumentNode | undefined = folder;
    while (current) {
      if (current.parentId === parentId) return true;
      current = documents.find(d => d.id === current.parentId);
    }
    return false;
  };
  
  // 搜索树形视图中的文档
  const searchTreeDocuments = useCallback((docs: DocumentNode[], keyword: string): DocumentNode[] => {
    if (!keyword.trim()) return docs;
    
    const searchTerm = keyword.toLowerCase().trim();
    
    const searchRecursive = (items: DocumentNode[]): DocumentNode[] => {
      const results: DocumentNode[] = [];
      
      for (const item of items) {
        // 如果当前项匹配搜索条件，添加它
        const matchesSearch = item.name.toLowerCase().includes(searchTerm);
        
        // 递归搜索子项
        const matchingChildren: DocumentNode[] = [];
        if (item.type === 'folder' && item.children && item.children.length > 0) {
          const childResults = searchRecursive(item.children);
          matchingChildren.push(...childResults);
        }
        
        // 如果当前项匹配或有匹配的子项，添加到结果中
        if (matchesSearch || matchingChildren.length > 0) {
          results.push({
            ...item,
            children: item.type === 'folder' ? matchingChildren : undefined
          });
        }
      }
      
      return results;
    };
    
    // 从顶级文档开始搜索
    const topLevelDocs = docs.filter(doc => doc.parentId === null);
    const filteredTopLevel = searchRecursive(topLevelDocs);
    
    // 构建完整的文档结构，包含匹配项及其父路径
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const buildFullTree = (filteredItems: DocumentNode[]): DocumentNode[] => {
      const resultMap = new Map<string, DocumentNode>();
      const addedIds = new Set<string>();
      
      // 先添加所有匹配的项
      const addItemWithParents = (item: DocumentNode) => {
        if (addedIds.has(item.id)) return;
        
        // 递归添加所有父级
        if (item.parentId) {
          const parent = docs.find(d => d.id === item.parentId);
          if (parent) {
            addItemWithParents(parent);
          }
        }
        
        // 创建项的副本，只包含必要的信息
        const itemCopy: DocumentNode = {
          ...item,
          children: []
        };
        
        resultMap.set(item.id, itemCopy);
        addedIds.add(item.id);
        
        // 添加到父项的children中
        if (item.parentId && resultMap.has(item.parentId)) {
          const parent = resultMap.get(item.parentId)!;
          if (!parent.children) parent.children = [];
          parent.children.push(itemCopy);
        }
      };
      
      // 处理所有匹配的顶级项
      for (const item of filteredTopLevel) {
        addItemWithParents(item);
      }
      
      // 返回顶级结果
      return Array.from(resultMap.values()).filter(item => !item.parentId);
    };
    
    return buildFullTree(filteredTopLevel);
  }, [documents]);

  // 加载文档树
  const loadDocuments = useCallback(async () => {
    setLoading(true);
    try {
      const response = await documentAPI.getDocumentTree();
      console.log('文档列表API响应:', response);
      
      // 更健壮的API响应处理
      if (response) {
        // 检查response的结构，支持多种可能的格式
        let documentData = [];
        if (Array.isArray(response)) {
          documentData = response;
        } else if (Array.isArray(response.data)) {
          documentData = response.data;
        } else if (typeof response === 'object') {
          console.warn('文档列表响应格式不匹配预期:', response);
          // 尝试从不同可能的字段中提取数据
          documentData = response.items || response.documents || [];
        }
        
        console.log('文档列表数据:', documentData.length, '项');
        // 确保数据经过规范化处理
        const normalizedData = normalizeDocuments(documentData);
        setDocuments(normalizedData);
      } else {
        console.warn('文档列表响应为空:', response);
        setDocuments([]);
      }
    } catch (error: unknown) {
      console.error('加载文档失败:', error);
      const errorMessage = (error as { message?: string })?.message || '加载文档列表失败';
      message.error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, [normalizeDocuments]);

  // 加载所有标签
  const loadAllTags = useCallback(async () => {
    try {
      const response = await documentAPI.getAllTags();
      if (response && response.data) {
        setAllTags(response.data);
      }
    } catch (error) {
      console.error('加载标签失败:', error);
    }
  }, []);

  useEffect(() => {
    if (activeTab === 'documents') {
      loadDocuments();
      loadAllTags();
    }
  }, [activeTab, loadDocuments, loadAllTags]);

  // 计算当前文件夹下的文档 + 搜索 + 排序 + 高级搜索
  const filteredDocuments = useMemo(() => {
    let list = documents.filter(doc => doc.parentId === selectedFolderId);
    
    // 应用高级搜索条件
    if (showAdvancedSearch) {
      if (advancedSearchParams.author) {
        list = list.filter(d => d.author && d.author.toLowerCase().includes(advancedSearchParams.author.toLowerCase()));
      }
      if (advancedSearchParams.startDate) {
        list = list.filter(d => new Date(d.updatedAt) >= advancedSearchParams.startDate!);
      }
      if (advancedSearchParams.endDate) {
        list = list.filter(d => new Date(d.updatedAt) <= advancedSearchParams.endDate!);
      }
      if (advancedSearchParams.isFavorite) {
        list = list.filter(d => d.isFavorite === true);
      }
      if (advancedSearchParams.minSize > 0) {
        list = list.filter(d => (d.size || 0) >= advancedSearchParams.minSize);
      }
      if (advancedSearchParams.maxSize < 100) {
        list = list.filter(d => (d.size || 0) <= advancedSearchParams.maxSize);
      }
    }
    
    // 应用关键词搜索
    const searched = keyword.trim()
      ? list.filter(d => d.name.toLowerCase().includes(keyword.trim().toLowerCase()))
      : list;
    
    // 排序
    const sorted = [...searched].sort((a, b) => {
      let v1: string | number = '';
      let v2: string | number = '';
      if (sortKey === 'name') {
        v1 = a.name || '';
        v2 = b.name || '';
        return sortOrder === 'asc'
          ? String(v1).localeCompare(String(v2))
          : String(v2).localeCompare(String(v1));
      }
      if (sortKey === 'type') {
        v1 = a.type;
        v2 = b.type;
        return sortOrder === 'asc'
          ? String(v1).localeCompare(String(v2))
          : String(v2).localeCompare(String(v1));
      }
      if (sortKey === 'author') {
        v1 = a.author || '';
        v2 = b.author || '';
        return sortOrder === 'asc'
          ? String(v1).localeCompare(String(v2))
          : String(v2).localeCompare(String(v1));
      }
      if (sortKey === 'size') {
        v1 = a.size || 0;
        v2 = b.size || 0;
        return sortOrder === 'asc' ? (v1 as number) - (v2 as number) : (v2 as number) - (v1 as number);
      }
      // 默认按更新时间
      v1 = new Date(a.updatedAt || a.createdAt).getTime();
      v2 = new Date(b.updatedAt || b.createdAt).getTime();
      return sortOrder === 'asc' ? (v1 as number) - (v2 as number) : (v2 as number) - (v1 as number);
    });
    return sorted;
  }, [documents, selectedFolderId, keyword, sortKey, sortOrder, showAdvancedSearch, advancedSearchParams]);
  
  // 构建树形数据 - 确保使用规范化后的文档数据
  const treeData = useMemo(() => {
    if (treeKeyword.trim()) {
      // 搜索模式：返回搜索结果的树形结构
      return buildTree(searchTreeDocuments(documents, treeKeyword), null);
    }
    // 正常模式：返回完整树形结构
    return buildTree(documents, null);
  }, [documents, treeKeyword, buildTree, searchTreeDocuments]);


  
  // 文件夹选择树数据
  const folderSelectData = useMemo(() => {
    return buildFolderTreeForSelection(documents, movingItem?.id);
  }, [documents, movingItem]);

  // 创建文档
  const handleCreateDocument = async () => {
    if (creatingDoc) return;
    if (!newDocName.trim()) {
      message.warning('请输入文档名称');
      return;
    }
    try {
      setCreatingDoc(true);
      const name = generateUniqueName(newDocName.trim());
      const params: CreateDocumentParams = {
        name,
        type: 'document',
        parentId: selectedFolderId,
        content: '<h1>新文档</h1><p>开始编辑你的文档...</p>'
      };
      await documentAPI.createDocument(params);
      message.success('文档创建成功');
      setShowCreateModal(false);
      setNewDocName('');
      loadDocuments();
    } catch (error) {
      console.error('创建文档失败:', error);
      message.error('创建文档失败');
    } finally {
      setCreatingDoc(false);
    }
  };

  // 创建文件夹
  const handleCreateFolder = async () => {
    if (creatingFolder) return;
    if (!newFolderName.trim()) {
      message.warning('请输入文件夹名称');
      return;
    }
    try {
      setCreatingFolder(true);
      const name = generateUniqueName(newFolderName.trim());
      const params: CreateDocumentParams = {
        name,
        type: 'folder',
        parentId: selectedFolderId
      };
      await documentAPI.createDocument(params);
      message.success('文件夹创建成功');
      setShowCreateFolderModal(false);
      setNewFolderName('');
      loadDocuments();
    } catch (error) {
      console.error('创建文件夹失败:', error);
      message.error('创建文件夹失败');
    } finally {
      setCreatingFolder(false);
    }
  };

  // 永久删除文档
  const handleDeleteDocument = useCallback(async (id: string) => {
    try {
      await documentAPI.deleteDocument(id);
      message.success('删除成功');
      
      // 立即从列表中移除该文档（优化用户体验）
      setDocuments(prevDocs => {
        const removeFromTree = (docs: DocumentNode[]): DocumentNode[] => {
          return docs
            .filter(doc => doc.id !== id)
            .map(doc => {
              if (doc.children && doc.children.length > 0) {
                return {
                  ...doc,
                  children: removeFromTree(doc.children)
                };
              }
              return doc;
            });
        };
        return removeFromTree(prevDocs);
      });
      
      // 如果该文档在选中列表中，也移除
      setSelectedRowKeys(prev => prev.filter(key => key !== id));
      
      // 延迟刷新列表以确保后端数据已更新
      setTimeout(() => {
        loadDocuments();
      }, 300);
    } catch (error: unknown) {
      console.error('删除失败:', error);
      const errorMessage = (error as { message?: string; data?: { message?: string } })?.message || (error as { data?: { message?: string } })?.data?.message || '删除失败';
      message.error(errorMessage);
      // 失败时刷新列表以恢复状态
      loadDocuments();
    }
  }, [loadDocuments]);

  // 打开文档
  const handleOpenDocument = useCallback((doc: DocumentNode) => {
    if (doc.type === 'folder') {
      setSelectedFolderId(doc.id);
      setSelectedRowKeys([]);
    } else {
      navigate(`/doc-collab?id=${doc.id}`);
    }
  }, [navigate]);

  // 面包屑路径
  const breadcrumb = useMemo(() => {
    if (!selectedFolderId) return [];
    const idToNode = new Map(documents.map(d => [d.id, d]));
    const path: DocumentNode[] = [];
    let current: DocumentNode | undefined = idToNode.get(selectedFolderId);
    while (current) {
      path.unshift(current);
      current = current.parentId ? idToNode.get(current.parentId) : undefined;
    }
    return path;
  }, [documents, selectedFolderId]);

  // 批量删除
  const handleBatchDelete = useCallback(async () => {
    if (selectedRowKeys.length === 0) return;
    const idsToDelete = selectedRowKeys as string[];
    try {
      // 直接永久删除
      await Promise.all(idsToDelete.map(id => documentAPI.deleteDocument(id)));
      
      // 立即从列表中移除这些文档（优化用户体验）
      setDocuments(prevDocs => {
        const removeFromTree = (docs: DocumentNode[]): DocumentNode[] => {
          return docs
            .filter(doc => !idsToDelete.includes(doc.id))
            .map(doc => {
              if (doc.children && doc.children.length > 0) {
                return {
                  ...doc,
                  children: removeFromTree(doc.children)
                };
              }
              return doc;
            });
        };
        return removeFromTree(prevDocs);
      });
      
      message.success(`已批量删除 (${idsToDelete.length} 项)`);
      setSelectedRowKeys([]);
      
      // 延迟刷新列表以确保后端数据已更新
      setTimeout(() => {
        loadDocuments();
      }, 300);
    } catch (error: unknown) {
      console.error('批量删除失败:', error);
      const errorMessage = (error as { message?: string; data?: { message?: string } })?.message || (error as { data?: { message?: string } })?.data?.message || '批量删除失败，请重试';
      message.error(errorMessage);
      // 失败时刷新列表以恢复状态
      loadDocuments();
    }
  }, [selectedRowKeys, loadDocuments]);



  // 取消分享
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const handleCancelShare = useCallback(async (id: string) => {
    try {
      await documentAPI.cancelShare(id);
      message.success('已取消分享');
      loadDocuments();
    } catch (error) {
      console.error('取消分享失败:', error);
      message.error('取消分享失败');
    }
  }, [loadDocuments]);

  // 批量移动
  const handleBatchMove = useCallback(async () => {
    if (selectedRowKeys.length === 0 || batchMovingTarget === undefined) return;
    try {
      await documentAPI.batchMoveDocuments(selectedRowKeys as string[], batchMovingTarget || '');
      message.success('批量移动成功');
      setSelectedRowKeys([]);
      setShowBatchMoveModal(false);
      setBatchMovingTarget(null);
      loadDocuments();
    } catch (error) {
      console.error('批量移动失败:', error);
      message.error('批量移动失败');
    }
  }, [selectedRowKeys, batchMovingTarget, loadDocuments]);

  // 批量复制
  const handleBatchCopy = useCallback(async () => {
    if (selectedRowKeys.length === 0 || batchCopyTarget === undefined) return;
    try {
      setCopyLoading(true);
      await documentAPI.batchCopyDocuments(selectedRowKeys as string[], batchCopyTarget || '');
      message.success('批量复制成功');
      setSelectedRowKeys([]);
      setShowBatchCopyModal(false);
      setBatchCopyTarget(null);
      loadDocuments();
    } catch (error) {
      console.error('批量复制失败:', error);
      message.error('批量复制失败');
    } finally {
      setCopyLoading(false);
    }
  }, [selectedRowKeys, batchCopyTarget, loadDocuments]);

  // 批量重命名
  const handleBatchRename = useCallback(async () => {
    if (selectedRowKeys.length === 0 || !batchRenamePrefix.trim()) return;
    try {
      await documentAPI.batchRenameDocuments(selectedRowKeys as string[], {
        prefix: batchRenamePrefix,
        startNumber: batchRenameStartNumber
      });
      message.success('批量重命名成功');
      setSelectedRowKeys([]);
      setShowBatchRenameModal(false);
      setBatchRenamePrefix('');
      setBatchRenameStartNumber(1);
      loadDocuments();
    } catch (error) {
      console.error('批量重命名失败:', error);
      message.error('批量重命名失败');
    }
  }, [selectedRowKeys, batchRenamePrefix, batchRenameStartNumber, loadDocuments]);

  // 批量添加标签
  const handleBatchTag = useCallback(async () => {
    if (selectedRowKeys.length === 0 || batchSelectedTags.length === 0) return;
    try {
      // 将标签 ID 转换为标签名称
      const tagNames = batchSelectedTags.map(tagId => {
        const tag = allTags.find(t => t.id === tagId);
        return tag ? tag.name : tagId;
      });
      await documentAPI.batchAddTags(selectedRowKeys as string[], tagNames);
      message.success('批量添加标签成功');
      setSelectedRowKeys([]);
      setShowBatchTagModal(false);
      setBatchSelectedTags([]);
      loadDocuments();
    } catch (error) {
      console.error('批量添加标签失败:', error);
      message.error('批量添加标签失败');
    }
  }, [selectedRowKeys, batchSelectedTags, allTags, loadDocuments]);


  // 分享文档
  const handleShareDocument = useCallback(async () => {
    if (!sharingItem) return;
    try {
      const response = await documentAPI.shareDocument(sharingItem.id, shareConfig);
      message.success('分享成功');
      // 复制分享链接到剪贴板
      if (response && response.shareUrl) {
        await navigator.clipboard.writeText(response.shareUrl);
        message.success('分享链接已复制到剪贴板');
      }
      setShowShareModal(false);
      setSharingItem(null);
      setShareConfig({ expireDays: 7, password: '', downloadLimit: 100, permissions: 'view' });
    } catch (error) {
      console.error('分享失败:', error);
      message.error('分享失败');
    }
  }, [sharingItem, shareConfig]);

  // 准备分享
  const prepareShare = useCallback((item: DocumentNode) => {
    setSharingItem(item);
    setShareConfig({ expireDays: 7, password: '', downloadLimit: 100, permissions: 'view' });
    setShowShareModal(true);
  }, []);

  // 上传文件
  const handleUpload = useCallback(async (files: File[]) => {
    if (files.length === 0) return;
    try {
      for (const file of files) {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('parentId', selectedFolderId || '');
        await documentAPI.uploadDocument(formData);
      }
      message.success(`成功上传 ${files.length} 个文件`);
      loadDocuments();
      setShowUploadModal(false);
      setFileList([]);
    } catch (error) {
      console.error('上传失败:', error);
      message.error('上传失败');
    }
  }, [selectedFolderId, loadDocuments]);

  // 拖放排序
  const handleDragStart = useCallback((e: React.DragEvent, item: DocumentNode) => {
    setIsDragging(true);
    setDraggedItem(item);
    e.dataTransfer.effectAllowed = 'move';
  }, []);

  const handleDragOver = useCallback((e: React.DragEvent, itemId: string) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
    if (draggedItem && draggedItem.id !== itemId) {
      setDraggedOverItem(itemId);
    }
  }, [draggedItem]);

  const handleDragEnd = useCallback(() => {
    setIsDragging(false);
    setDraggedItem(null);
    setDraggedOverItem(null);
  }, []);

  const handleDrop = useCallback(async (e: React.DragEvent, targetId: string) => {
    e.preventDefault();
    if (!draggedItem || draggedItem.id === targetId) {
      handleDragEnd();
      return;
    }
    
    try {
      await documentAPI.reorderDocument(draggedItem.id, targetId);
      message.success('排序成功');
      loadDocuments();
    } catch (error) {
      console.error('排序失败:', error);
      message.error('排序失败');
    } finally {
      handleDragEnd();
    }
  }, [draggedItem, handleDragEnd, loadDocuments]);

  // 高级搜索
  const handleAdvancedSearch = useCallback(() => {
    // 高级搜索逻辑已集成到 filteredDocuments 中
    message.success('搜索条件已应用');
    setShowAdvancedSearch(false);
  }, []);

  // 批量导出
  const handleBatchExport = useCallback(async () => {
    if (selectedRowKeys.length === 0) return;
    try {
      const response = await documentAPI.exportDocuments(selectedRowKeys as string[]);
      // 处理导出响应，通常是下载文件
      const blob = response instanceof Blob ? response : new Blob([JSON.stringify(response)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `documents-export-${new Date().toISOString().split('T')[0]}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      
      message.success('批量导出成功');
      setShowBatchExportModal(false);
    } catch (error) {
      console.error('批量导出失败:', error);
      message.error('批量导出失败');
    }
  }, [selectedRowKeys]);

  // 批量移动的文件夹选择树数据
  const batchMoveFolderSelectData = useMemo(() => {
    return buildFolderTreeForSelection(documents);
  }, [documents]);

  // 收藏的文档列表
  const favoriteDocuments = useMemo(() => {
    // 递归查找所有层级中的收藏文档
    const findFavorites = (docs: DocumentNode[]): DocumentNode[] => {
      const favorites: DocumentNode[] = [];
      
      docs.forEach(doc => {
        // 检查当前文档是否被收藏
        if (doc.isFavorite) {
          favorites.push(doc);
        }
        
        // 递归检查子文档
        if (doc.type === 'folder' && doc.children && doc.children.length > 0) {
          favorites.push(...findFavorites(doc.children));
        }
      });
      
      return favorites;
    };
    
    // 从所有文档中查找收藏的文档
    return findFavorites(documents);
  }, [documents]);

  // 切换文档收藏状态
  const handleToggleFavorite = useCallback(async (doc: DocumentNode) => {
    try {
      // 先调用API保存到服务器
      await documentAPI.updateDocument(doc.id, {
        isFavorite: !doc.isFavorite
      });
      
      // API调用成功后再更新本地状态
      setDocuments(prevDocs => {
        const updateFavorites = (docs: DocumentNode[]): DocumentNode[] => {
          return docs.map(item => {
            if (item.id === doc.id) {
              return { ...item, isFavorite: !item.isFavorite };
            }
            if (item.children && item.children.length > 0) {
              return {
                ...item,
                children: updateFavorites(item.children)
              };
            }
            return item;
          });
        };
        return updateFavorites(prevDocs);
      });
      
      message.success(doc.isFavorite ? '已取消收藏' : '收藏成功');
      
      // 不需要额外的重新加载，因为我们已经手动更新了本地状态
    } catch (error) {
      console.error('更新收藏状态失败:', error);
      message.error('操作失败');
      // 出错时重新加载文档以确保状态正确
      loadDocuments();
    }
  }, [loadDocuments]);

  // 将 DocumentNode 转换为 Ant Design Tree 的 TreeNode 格式
  const convertToTreeNodes = useCallback((nodes: DocumentNode[]): Array<{
    title: React.ReactNode;
    key: string;
    isLeaf: boolean;
    icon: React.ReactNode;
    children?: Array<{
      title: React.ReactNode;
      key: string;
      isLeaf: boolean;
      icon: React.ReactNode;
      children?: Array<{
        title: React.ReactNode;
        key: string;
        isLeaf: boolean;
        icon: React.ReactNode;
      }>;
    }>;
  }> => {
    return nodes.map(node => {
      // 创建右键菜单
      const contextMenu = (
        <Menu
          items={[
            {
              key: 'open',
              label: node.type === 'folder' ? '打开文件夹' : '打开文档',
              icon: <FileText size={16} />,
              onClick: () => handleOpenDocument(node)
            },
            {
              key: 'copy',
              label: '复制',
              icon: <Copy size={16} />,
              onClick: () => {
                // 设置复制目标为当前文件夹
                setBatchCopyTarget(selectedFolderId);
                setShowBatchCopyModal(true);
              }
            },
            {
              key: 'rename',
              label: '重命名',
              icon: <Edit2 size={16} />,
              onClick: () => prepareRename(node)
            },
            {
              key: 'move',
              label: '移动',
              icon: <Move size={16} />,
              onClick: () => prepareMove(node)
            },
            node.type === 'document' && {
              key: 'share',
              label: '分享',
              icon: <Share2 size={16} />,
              onClick: () => prepareShare(node)
            },
            node.type === 'document' && {
              key: 'favorite',
              label: node.isFavorite ? '取消收藏' : '收藏',
              icon: node.isFavorite ? <Star size={16} /> : <StarOff size={16} />,
              onClick: () => handleToggleFavorite(node)
            },
            {
              key: 'delete',
              label: '删除',
              danger: true,
              onClick: () => handleDeleteDocument(node.id)
            }
          ].filter(Boolean) as Array<{ key: string; label: string; icon?: React.ReactNode; onClick: () => void; danger?: boolean }>}
        />
      );
      
      return {
        title: (
          <Dropdown overlay={contextMenu} trigger={['contextMenu']}>
            <div 
              className={`flex items-center justify-between group cursor-pointer ${draggedOverItem === node.id ? 'bg-blue-100 dark:bg-blue-900/30' : ''}`}
              draggable
              onDragStart={(e) => handleDragStart(e, node)}
              onDragOver={(e) => handleDragOver(e, node.id)}
              onDragEnd={handleDragEnd}
              onDrop={(e) => handleDrop(e, node.id)}
            >
              <div className="flex items-center space-x-2 flex-1">
                {node.type === 'folder' ? (
                  <Folder className="text-blue-500" size={16} />
                ) : (
                  <FileText className="text-gray-500" size={16} />
                )}
                <span className="flex-1">{(node.name && node.name.trim()) ? node.name : '未命名'}</span>
                {node.tags && node.tags.length > 0 && (
                  <div className="flex flex-wrap gap-1">
                    {node.tags.slice(0, 2).map((tag, index) => (
                      <Tag key={index} color="blue">{tag}</Tag>
                    ))}
                    {node.tags.length > 2 && (
                      <Tag color="default">+{node.tags.length - 2}</Tag>
                    )}
                  </div>
                )}
              </div>
              <Space size="small" className="opacity-0 group-hover:opacity-100 transition-opacity">
                {node.type === 'document' && (
                    <>
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleOpenDocument(node);
                      }}
                    >
                      打开
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleToggleFavorite(node);
                      }}
                      className={node.isFavorite ? 'text-yellow-500' : ''}
                    >
                      {node.isFavorite ? <Star size={14} /> : <StarOff size={14} />}
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={(e) => {
                        e.stopPropagation();
                        prepareShare(node);
                      }}
                    >
                      <Share2 size={14} />
                    </Button>
                    </>
                )}
                <Button
                  size="sm"
                  variant="outline"
                  onClick={(e) => {
                    e.stopPropagation();
                    prepareRename(node);
                  }}
                >
                  <Edit2 size={14} />
                </Button>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={(e) => {
                    e.stopPropagation();
                    prepareMove(node);
                  }}
                >
                  <Move size={14} />
                </Button>
                <Popconfirm
                  title="确定要删除吗？"
                  description="此操作不可恢复"
                  onConfirm={(e) => {
                    e?.stopPropagation();
                    handleDeleteDocument(node.id);
                  }}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button 
                    size="sm" 
                    variant="danger"
                    onClick={(e) => {
                      e.stopPropagation();
                    }}
                  >
                    删除
                  </Button>
                </Popconfirm>
              </Space>
            </div>
          </Dropdown>
        ),
        key: node.id,
        isLeaf: node.type === 'document',
        icon: node.type === 'folder' ? <Folder className="text-blue-500" size={16} /> : <FileText className="text-gray-500" size={16} />,
        children: node.type === 'folder' && node.children ? convertToTreeNodes(node.children) : undefined
      };
    });
  }, [handleOpenDocument, handleDeleteDocument, prepareRename, prepareMove, selectedFolderId, prepareShare, handleToggleFavorite, draggedOverItem, handleDragStart, handleDragOver, handleDragEnd, handleDrop]);


  // 表格列定义
  const columns = [
    {
      title: '',
      dataIndex: 'checkbox',
      width: 40,
      render: () => null,
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: DocumentNode) => (
        <div 
          className={`flex items-center space-x-2 cursor-pointer hover:text-blue-600 relative ${draggedOverItem === record.id ? 'bg-blue-100 dark:bg-blue-900/30' : ''}`}
          onClick={() => handleOpenDocument(record)}
          draggable
          onDragStart={(e) => handleDragStart(e, record)}
          onDragOver={(e) => handleDragOver(e, record.id)}
          onDragEnd={handleDragEnd}
          onDrop={(e) => handleDrop(e, record.id)}
        >
          {record.type === 'folder' ? (
            <Folder className="text-blue-500" size={18} />
          ) : (
            <>
              <FileText className="text-gray-500" size={18} />
              {record.isFavorite && (
                <Star className="text-yellow-500 absolute -top-1 -right-1" size={12} />
              )}
            </>
          )}
          {/* 使用规范化的名称显示，支持搜索高亮 */}
          <span className={searchHighlight && keyword ? 'relative' : ''}>
            {searchHighlight && keyword && text.toLowerCase().includes(keyword.toLowerCase()) ? (
              <>
                {text.split(new RegExp(`(${keyword})`, 'gi')).map((part, index) => (
                  part.toLowerCase() === keyword.toLowerCase() ? 
                    <span key={index} className="bg-yellow-200 dark:bg-yellow-800">{part}</span> : 
                    part
                ))}
              </>
            ) : (
              (text && text.trim()) ? text : '未命名'
            )}
          </span>
          {record.tags && record.tags.length > 0 && (
            <div className="flex flex-wrap gap-1 ml-2">
              {record.tags.map((tag, index) => (
                <Tag key={index} color="blue">{tag}</Tag>
              ))}
            </div>
          )}
        </div>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => (
        <span className={`px-2 py-1 rounded text-xs ${
          type === 'folder' 
            ? 'bg-blue-100 text-blue-700' 
            : 'bg-gray-100 text-gray-700'
        }`}>
          {type === 'folder' ? '文件夹' : '文档'}
        </span>
      ),
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      render: (author: string) => author || '-',
    },
    {
      title: '大小',
      dataIndex: 'size',
      key: 'size',
      render: (size: number) => {
        if (!size) return '-';
        if (size < 1024) return `${size} B`;
        if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
        return `${(size / (1024 * 1024)).toFixed(1)} MB`;
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: unknown, record: DocumentNode) => (
        <Space size="middle">
          {record.type === 'document' && (
            <>
              <Button
                size="sm"
                variant="outline"
                onClick={() => handleOpenDocument(record)}
              >
                打开
              </Button>
              <Button
                size="sm"
                variant="outline"
                onClick={() => handleToggleFavorite(record)}
                className={record.isFavorite ? 'text-yellow-500' : ''}
              >
                {record.isFavorite ? <Star size={14} /> : <StarOff size={14} />}
              </Button>
              <Button
                size="sm"
                variant="outline"
                onClick={() => prepareShare(record)}
              >
                <Share2 size={14} />
              </Button>
            </>
          )}
          <Button
            size="sm"
            variant="outline"
            onClick={() => prepareRename(record)}
          >
            <Edit2 size={14} className="mr-1" />
            重命名
          </Button>
          <Button
            size="sm"
            variant="outline"
            onClick={() => prepareMove(record)}
          >
            <Move size={14} className="mr-1" />
            移动
          </Button>
          <Popconfirm
            title="确定要删除吗？"
            description="此操作不可恢复"
            onConfirm={() => handleDeleteDocument(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button size="sm" variant="danger">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];


  // 网格视图渲染
  const renderGridView = () => {
    const items = filteredDocuments;
    
    return (
      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
        {items.map(item => (
          <div
            key={item.id}
            className={`p-4 border rounded-lg hover:shadow-md cursor-pointer transition-all ${isDark ? 'bg-slate-800/60 border-slate-700 text-slate-100' : 'bg-white border-slate-200 text-gray-900'} ${draggedOverItem === item.id ? (isDark ? 'ring-1 ring-blue-400 bg-blue-500/20' : 'ring-1 ring-blue-300 bg-blue-50') : ''}`}
            draggable
            onDragStart={(e) => handleDragStart(e, item)}
            onDragOver={(e) => handleDragOver(e, item.id)}
            onDragEnd={handleDragEnd}
            onDrop={(e) => handleDrop(e, item.id)}
          >
            <div className="flex justify-between items-start mb-2">
              {item.type === 'folder' ? (
                <Folder className="text-blue-500" size={24} />
              ) : (
                <FileText className="text-gray-500" size={24} />
              )}
              <Dropdown 
                overlay={
                  <Menu
                    items={[
                      {
                        key: 'open',
                        label: '打开',
                        onClick: () => handleOpenDocument(item)
                      },
                      {
                        key: 'rename',
                        label: '重命名',
                        onClick: () => prepareRename(item)
                      },
                      {
                        key: 'move',
                        label: '移动',
                        onClick: () => prepareMove(item)
                      },
                      item.type === 'document' && {
                        key: 'share',
                        label: '分享',
                        onClick: () => prepareShare(item)
                      },
                      item.type === 'document' && {
                        key: 'favorite',
                        label: item.isFavorite ? '取消收藏' : '收藏',
                        onClick: () => handleToggleFavorite(item)
                      },
                      {
                        key: 'delete',
                        label: '删除',
                        danger: true,
                        onClick: () => handleDeleteDocument(item.id)
                      }
                    ].filter(Boolean) as Array<{ key: string; label: string; icon?: React.ReactNode; onClick: () => void; danger?: boolean }>}
                  />
                }
              >
                <MoreHorizontal size={16} />
              </Dropdown>
            </div>
            <h3 
              className="font-medium mb-1 truncate" 
              onClick={() => handleOpenDocument(item)}
            >
              {(item.name && item.name.trim()) ? item.name : '未命名'}
            </h3>
            <p className="text-sm text-gray-500 mb-2">
              {new Date(item.updatedAt).toLocaleDateString()}
            </p>
            {item.tags && item.tags.length > 0 && (
              <div className="flex flex-wrap gap-1 mt-2">
                {item.tags.map((tag, index) => (
                  <Tag key={index} color="blue">{tag}</Tag>
                ))}
              </div>
            )}
            {item.isFavorite && (
              <Star className="text-yellow-500 absolute bottom-2 right-2" size={14} />
            )}
          </div>
        ))}
      </div>
    );
  };

  // 渲染文档内容的函数
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const renderDocumentContent = () => {
    if (activeTab === 'favorites') {
      return (
        <div className="p-4">
          <Table
            columns={columns}
            dataSource={documents.filter(doc => doc.isFavorite)}
            rowKey="id"
            loading={loading}
            pagination={false}
            rowSelection={{
              selectedRowKeys,
              onChange: setSelectedRowKeys,
            }}
            locale={{
              emptyText: '暂无收藏的文档'
            }}
          />
        </div>
      );
    }
    
    // 默认显示文档列表
    return (
      <div className="p-4">
        {loading ? (
          <div className="flex items-center justify-center py-8">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mr-3"></div>
            <span className={isDark ? 'text-gray-300' : 'text-gray-600'}>加载中...</span>
          </div>
        ) : filteredDocuments.length === 0 ? (
          <div className={`text-center py-8 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
            暂无文档，点击上方按钮创建
          </div>
        ) : viewMode === 'grid' ? (
          renderGridView()
        ) : viewMode === 'tree' ? (
          <div className={`${isDark ? 'bg-slate-800/60 border border-slate-700' : 'bg-slate-100 border border-slate-200'} rounded-lg p-4 transition-colors`}>
            {/* 树形视图搜索框 */}
            <div className="mb-4">
              <Input
                value={treeKeyword}
                onChange={(e) => setTreeKeyword(e.target.value)}
                placeholder="搜索文档或文件夹..."
                leftIcon={<Search size={16} />}
              />
              {treeKeyword && (
                <div className="text-xs text-gray-500 mt-1">
                  搜索结果：{searchTreeDocuments(documents, treeKeyword).length} 项
                </div>
              )}
            </div>
            {loading ? (
              <div className="flex items-center justify-center py-8">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mr-3"></div>
                <span className={isDark ? 'text-gray-300' : 'text-gray-600'}>加载中...</span>
              </div>
            ) : treeData.length === 0 ? (
              <div className={`text-center py-8 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
                {treeKeyword ? '没有找到匹配的文档或文件夹' : '暂无文档，点击上方按钮创建'}
              </div>
            ) : (
              <Tree
                treeData={convertToTreeNodes(treeData)}
                expandedKeys={expandedKeys}
                onExpand={setExpandedKeys}
                onSelect={(selectedKeys, info) => {
                  if (info.node && selectedKeys.length > 0) {
                    const node = documents.find(d => d.id === selectedKeys[0] as string);
                    if (node) {
                      if (node.type === 'folder') {
                        // 记录当前选中的文件夹，便于在树形视图下新建到该目录
                        setSelectedFolderId(node.id);
                        // 切换展开/折叠
                        if (expandedKeys.includes(node.id)) {
                          setExpandedKeys(expandedKeys.filter(k => k !== node.id));
                        } else {
                          setExpandedKeys([...expandedKeys, node.id]);
                        }
                      } else {
                        handleOpenDocument(node);
                      }
                    }
                  }
                }}
                showIcon
                blockNode
                className={isDark ? 'text-gray-100' : ''}
              />
            )}
          </div>
        ) : (
          // 判断当前文件夹是否允许拖拽排序
          selectedFolderId ? (
            <Table
              {...tableThemeProps}
              columns={columns}
              dataSource={filteredDocuments}
              rowKey="id"
              pagination={false}
              rowSelection={{
                selectedRowKeys,
                onChange: setSelectedRowKeys,
              }}
              locale={{
                emptyText: '暂无文档，点击上方按钮创建'
              }}
            />
          ) : (
            <Table
              {...tableThemeProps}
              columns={columns}
              dataSource={filteredDocuments}
              rowKey="id"
              pagination={false}
              rowSelection={{
                selectedRowKeys,
                onChange: setSelectedRowKeys,
              }}
              locale={{
                emptyText: '暂无文档，点击上方按钮创建'
              }}
            />
          )
        )}
      </div>
    );
  };
  
  return (
    <div className={`min-h-screen p-6 transition-colors duration-300 ${isDark ? 'bg-gray-900 text-gray-100' : 'bg-gray-50 text-gray-900'}`}>
      <div className="max-w-7xl mx-auto">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-2xl font-bold">文档列表</h1>
            <p className="text-sm text-gray-500 mt-1">{t('document.list.subtitle')}</p>
          </div>
        </div>
        
        <Card className={`overflow-hidden ${isDark ? 'bg-gray-800 border-gray-700' : 'bg-white'}`}>
          <Tabs 
            activeKey={activeTab}
            defaultActiveKey="documents" 
            onChange={(key) => setActiveTab(key as 'documents' | 'favorites')}
            className="w-full"
            items={[
              {
                key: 'documents',
                label: '我的文档',
                children: (
                  <>
                    {showAdvancedSearch && (
                      <div className={`p-4 ${isDark ? 'bg-gray-800' : 'bg-gray-50'}`}>
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                          <div>
                            <label className="block text-sm font-medium mb-1">作者</label>
                            <Input
                              value={advancedSearchParams.author}
                              onChange={(e) => setAdvancedSearchParams({...advancedSearchParams, author: e.target.value})}
                              placeholder="输入作者名称"
                            />
                          </div>
                          <div>
                            <label className="block text-sm font-medium mb-1">修改日期</label>
                            <DatePicker.RangePicker
                              onChange={(dates) => {
                                if (dates && dates[0] && dates[1]) {
                                  setAdvancedSearchParams({
                                    ...advancedSearchParams,
                                    startDate: dates[0].toDate(),
                                    endDate: dates[1].toDate()
                                  });
                                } else {
                                  setAdvancedSearchParams({
                                    ...advancedSearchParams,
                                    startDate: null,
                                    endDate: null
                                  });
                                }
                              }}
                            />
                          </div>
                          <div>
                            <label className="block text-sm font-medium mb-1">收藏文档</label>
                            <Checkbox
                              checked={advancedSearchParams.isFavorite}
                              onChange={(e) => setAdvancedSearchParams({...advancedSearchParams, isFavorite: e.target.checked})}
                            >
                              仅显示收藏文档
                            </Checkbox>
                          </div>
                        </div>
                        <div className="flex justify-end mt-4 space-x-2">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => {
                              setAdvancedSearchParams({
                                author: '',
                                startDate: null,
                                endDate: null,
                                minSize: 0,
                                maxSize: 100,
                                isFavorite: false
                              });
                              setShowAdvancedSearch(false);
                            }}
                          >
                            重置
                          </Button>
                          <Button variant="primary" size="sm" onClick={handleAdvancedSearch}>
                            搜索
                          </Button>
                        </div>
                      </div>
                    )}
                    <div className="py-4">
                    {/* 工具栏 */}
                    <div className="flex items-center justify-between mb-4 pb-4 border-b">
                      <div className="flex items-center space-x-2">
                        <Space>
                              <Button
                                variant={viewMode === 'tree' ? 'primary' : 'outline'}
                                size="sm"
                                onClick={() => setViewMode('tree')}
                              >
                                树形视图
                              </Button>
                              <Button
                                variant={viewMode === 'list' ? 'primary' : 'outline'}
                                size="sm"
                                onClick={() => setViewMode('list')}
                              >
                                列表视图
                              </Button>
                              <Button
                                variant={viewMode === 'grid' ? 'primary' : 'outline'}
                                size="sm"
                                onClick={() => setViewMode('grid')}
                              >
                                <Grid size={14} className="mr-1" />
                                网格视图
                              </Button>
                            </Space>
                        {viewMode === 'list' && (
                          <div className="ml-3 text-sm">
                            <span
                              className="cursor-pointer text-blue-600"
                              onClick={() => {
                                setSelectedFolderId(null);
                                setSelectedRowKeys([]);
                              }}
                            >
                              根目录
                            </span>
                            {breadcrumb.map((node, idx) => (
                              <span key={node.id}>
                                <span className="mx-1 text-gray-400">/</span>
                                <span
                                  className={`cursor-pointer ${idx === breadcrumb.length - 1 ? 'font-semibold' : 'text-blue-600'}`}
                                  onClick={() => {
                                    setSelectedFolderId(node.id);
                                    setSelectedRowKeys([]);
                                  }}
                                >
                                  {node.name}
                                </span>
                              </span>
                            ))}
                          </div>
                        )}
                      </div>
                      <Space>
                        {viewMode === 'list' && (
                          <>
                            <div className="flex items-center" style={{ width: 220 }}>
                              <Input
                                value={keyword}
                                onChange={(e) => setKeyword(e.target.value)}
                                placeholder="搜索名称..."
                                rightIcon={
                                  <button
                                    onClick={() => setShowAdvancedSearch(!showAdvancedSearch)}
                                    className="text-gray-400 hover:text-gray-600"
                                  >
                                    <Filter size={14} />
                                  </button>
                                }
                              />
                            </div>
                            <Select
                              value={`${sortKey}:${sortOrder}`}
                              onChange={(v) => {
                                const [k, o] = v.split(':') as [typeof sortKey, typeof sortOrder];
                                setSortKey(k);
                                setSortOrder(o);
                              }}
                              style={{ width: 180 }}
                              options={[
                                { label: '按更新时间(新→旧)', value: 'updatedAt:desc' },
                                { label: '按更新时间(旧→新)', value: 'updatedAt:asc' },
                                { label: '按名称(A→Z)', value: 'name:asc' },
                                { label: '按名称(Z→A)', value: 'name:desc' },
                                { label: '按类型', value: 'type:asc' },
                              ]}
                            />
                          </>
                        )}
                        <Button
                          variant="primary"
                          size="sm"
                          onClick={() => setShowCreateFolderModal(true)}
                        >
                          <FolderPlus size={16} className="mr-2 inline" />
                          新建文件夹
                        </Button>
                        <Button
                        variant="primary"
                        size="sm"
                        onClick={() => setShowCreateModal(true)}
                      >
                        <Plus size={16} className="mr-2 inline" />
                        新建文档
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setShowUploadModal(true)}
                      >
                        <UploadIcon size={16} className="mr-2 inline" />
                        批量上传
                      </Button>
                        {viewMode === 'list' && selectedRowKeys.length > 0 && (
                          <Dropdown
                            overlay={
                              <Menu
                                items={[
                                  {
                                    key: 'move',
                                    label: '批量移动',
                                    icon: <Move size={14} />,
                                    onClick: () => {
                                      setBatchMovingTarget(selectedFolderId);
                                      setShowBatchMoveModal(true);
                                    }
                                  },
                                  {
                                    key: 'copy',
                                    label: '批量复制',
                                    icon: <Copy size={14} />,
                                    onClick: () => {
                                      setBatchCopyTarget(selectedFolderId);
                                      setShowBatchCopyModal(true);
                                    }
                                  },
                                  {
                                    key: 'rename',
                                    label: '批量重命名',
                                    icon: <Edit2 size={14} />,
                                    onClick: () => setShowBatchRenameModal(true)
                                  },
                                  {
                                    key: 'tag',
                                    label: '批量标签',
                                    icon: <Tag />,
                                    onClick: () => setShowBatchTagModal(true)
                                  },
                                  {
                                    key: 'export',
                                    label: '批量导出',
                                    icon: <Download size={14} />,
                                    onClick: () => setShowBatchExportModal(true)
                                  },
                                  {
                                    type: 'divider'
                                  },
                                  {
                                    key: 'delete',
                                    label: '批量删除',
                                    icon: <Trash2 size={14} />,
                                    danger: true,
                                    onClick: () => {
                                      Modal.confirm({
                                        title: `确定批量删除选中的 ${selectedRowKeys.length} 项吗？`,
                                        content: '此操作不可恢复',
                                        okText: '确定',
                                        cancelText: '取消',
                                        onOk: handleBatchDelete
                                      });
                                    }
                                  }
                                ]}
                              />
                            }
                            trigger={['click']}
                          >
                            <Button variant="outline" size="sm">
                              <MoreHorizontal size={14} className="mr-1" />
                              批量操作 ({selectedRowKeys.length})
                            </Button>
                          </Dropdown>
                        )}
                      </Space>
                    </div>

                    {/* 文档列表/树形视图 */}
                    {viewMode === 'tree' ? (
                      <div className={`${isDark ? 'bg-slate-800/60 border border-slate-700' : 'bg-slate-100 border border-slate-200'} rounded-lg p-4 transition-colors`}>
                        {/* 树形视图搜索框 */}
                        <div className="mb-4">
                          <Input
                            value={treeKeyword}
                            onChange={(e) => setTreeKeyword(e.target.value)}
                            placeholder="搜索文档或文件夹..."
                            leftIcon={<Search size={16} />}
                          />
                          {treeKeyword && (
                            <div className="text-xs text-gray-500 mt-1">
                              搜索结果：{searchTreeDocuments(documents, treeKeyword).length} 项
                            </div>
                          )}
                        </div>
                        {loading ? (
                          <div className="flex items-center justify-center py-8">
                            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mr-3"></div>
                            <span className={isDark ? 'text-gray-300' : 'text-gray-600'}>加载中...</span>
                          </div>
                        ) : treeData.length === 0 ? (
                          <div className={`text-center py-8 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
                            {treeKeyword ? '没有找到匹配的文档或文件夹' : '暂无文档，点击上方按钮创建'}
                          </div>
                        ) : (
                          <Tree
                            treeData={convertToTreeNodes(treeData)}
                            expandedKeys={expandedKeys}
                            onExpand={setExpandedKeys}
                            onSelect={(selectedKeys, info) => {
                              if (info.node && selectedKeys.length > 0) {
                                const node = documents.find(d => d.id === selectedKeys[0] as string);
                                if (node) {
                                  if (node.type === 'folder') {
                                    // 记录当前选中的文件夹，便于在树形视图下新建到该目录
                                    setSelectedFolderId(node.id);
                                    // 切换展开/折叠
                                    if (expandedKeys.includes(node.id)) {
                                      setExpandedKeys(expandedKeys.filter(k => k !== node.id));
                                    } else {
                                      setExpandedKeys([...expandedKeys, node.id]);
                                    }
                                  } else {
                                    handleOpenDocument(node);
                                  }
                                }
                              }
                            }}
                            showIcon
                            blockNode
                            className={isDark ? 'text-gray-100' : ''}
                          />
                        )}
                      </div>
                    ) : viewMode === 'grid' ? (
                      renderGridView()
                    ) : (
                      // 判断当前文件夹是否允许拖拽排序
                      selectedFolderId ? (
                        <Table
                          {...tableThemeProps}
                          columns={columns}
                          dataSource={filteredDocuments}
                          rowKey="id"
                          pagination={false}
                          rowSelection={{
                            selectedRowKeys,
                            onChange: setSelectedRowKeys,
                          }}
                          locale={{
                            emptyText: '暂无文档，点击上方按钮创建'
                          }}
                        />
                      ) : (
                        <Table
                          {...tableThemeProps}
                          columns={columns}
                          dataSource={filteredDocuments}
                          rowKey="id"
                          pagination={false}
                          rowSelection={{
                            selectedRowKeys,
                            onChange: setSelectedRowKeys,
                          }}
                          locale={{
                            emptyText: '暂无文档，点击上方按钮创建'
                          }}
                        />
                      )
                    )}
                  </div>
                  </>
                )
              },
              {
                key: 'favorites',
                label: `收藏文档 (${favoriteDocuments.length})`,
                children: (
                  <div className="py-4">
                    {loading ? (
                      <div className="flex items-center justify-center py-8">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mr-3"></div>
                        <span className={isDark ? 'text-gray-300' : 'text-gray-600'}>加载中...</span>
                      </div>
                    ) : (
                      <Table
                        columns={columns}
                        dataSource={favoriteDocuments}
                        rowKey="id"
                        pagination={false}
                        rowSelection={{
                          selectedRowKeys,
                          onChange: setSelectedRowKeys,
                        }}
                        locale={{
                          emptyText: '暂无收藏文档'
                        }}
                      />
                    )}
                  </div>
                )
              }
            ]}
          />
        </Card>
      </div>

      {/* 批量移动弹窗 */}
      <Modal
        open={showBatchMoveModal}
        onCancel={() => {
          setShowBatchMoveModal(false);
          setBatchMovingTarget(null);
        }}
        title={`批量移动 (${selectedRowKeys.length} 项)`}
        footer={null}
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-2">目标文件夹</label>
            <Select
              value={batchMovingTarget}
              onChange={(value) => setBatchMovingTarget(value)}
              placeholder="选择目标文件夹"
              style={{ width: '100%' }}
              options={batchMoveFolderSelectData}
            />
          </div>
          <div className="flex justify-end space-x-2">
            <Button variant="outline" onClick={() => setShowBatchMoveModal(false)}>
              取消
            </Button>
            <Button variant="primary" onClick={handleBatchMove} disabled={batchMovingTarget === null || batchMovingTarget === undefined}>
              移动
            </Button>
          </div>
        </div>
      </Modal>

      {/* 批量导出弹窗 */}
      <Modal
        open={showBatchExportModal}
        onCancel={() => setShowBatchExportModal(false)}
        title={`批量导出 (${selectedRowKeys.length} 项)`}
        footer={null}
      >
        <div className="space-y-4">
          <div className="p-4 bg-blue-50 dark:bg-blue-900/30 rounded">
            <p>将导出 {selectedRowKeys.length} 个文档或文件夹</p>
            <p className="text-sm text-gray-600 dark:text-gray-300 mt-1">导出格式: ZIP压缩包</p>
          </div>
          <div className="flex justify-end space-x-2">
            <Button variant="outline" onClick={() => setShowBatchExportModal(false)}>
              取消
            </Button>
            <Button variant="primary" onClick={handleBatchExport}>
              开始导出
            </Button>
          </div>
        </div>
      </Modal>

      {/* 批量复制弹窗 */}
      <Modal
        open={showBatchCopyModal}
        onCancel={() => {
          setShowBatchCopyModal(false);
          setBatchCopyTarget(null);
        }}
        title={`批量复制 (${selectedRowKeys.length} 项)`}
        footer={null}
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-2">目标文件夹</label>
            <Select
              value={batchCopyTarget}
              onChange={(value) => setBatchCopyTarget(value)}
              placeholder="选择目标文件夹"
              style={{ width: '100%' }}
              options={batchMoveFolderSelectData}
            />
          </div>
          <div className="flex justify-end space-x-2">
            <Button variant="outline" onClick={() => {
              setShowBatchCopyModal(false);
              setBatchCopyTarget(null);
            }} disabled={copyLoading}>
              取消
            </Button>
            <Button variant="primary" onClick={handleBatchCopy} disabled={copyLoading || batchCopyTarget === null || batchCopyTarget === undefined}>
              {copyLoading ? '复制中...' : '复制'}
            </Button>
          </div>
        </div>
      </Modal>

      {/* 创建文档弹窗 */}
      <Modal
        open={showCreateModal}
        onCancel={() => {
          setShowCreateModal(false);
          setNewDocName('');
        }}
        title="新建文档"
        footer={null}
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-2">文档名称</label>
            <Input
              value={newDocName}
              onChange={(e) => setNewDocName(e.target.value)}
              placeholder="请输入文档名称"
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  handleCreateDocument();
                }
              }}
            />
          </div>
          <div className="flex justify-end space-x-2">
            <Button variant="outline" onClick={() => setShowCreateModal(false)} disabled={creatingDoc}>
              取消
            </Button>
            <Button variant="primary" onClick={handleCreateDocument} disabled={creatingDoc}>
              创建
            </Button>
          </div>
        </div>
      </Modal>

      {/* 创建文件夹弹窗 */}
      <Modal
        open={showCreateFolderModal}
        onCancel={() => {
          setShowCreateFolderModal(false);
          setNewFolderName('');
        }}
        title="新建文件夹"
        footer={null}
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-2">文件夹名称</label>
            <Input
              value={newFolderName}
              onChange={(e) => setNewFolderName(e.target.value)}
              placeholder="请输入文件夹名称"
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  handleCreateFolder();
                }
              }}
            />
          </div>
          <div className="flex justify-end space-x-2">
            <Button variant="outline" onClick={() => setShowCreateFolderModal(false)} disabled={creatingFolder}>
              取消
            </Button>
            <Button variant="primary" onClick={handleCreateFolder} disabled={creatingFolder}>
              创建
            </Button>
          </div>
        </div>
      </Modal>

      {/* 重命名弹窗 */}
      <Modal
        open={showRenameModal}
        onCancel={() => {
          setShowRenameModal(false);
          setRenamingItem(null);
          setNewName('');
        }}
        title={`重命名${renamingItem?.type === 'folder' ? '文件夹' : '文档'}`}
        footer={null}
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-2">新名称</label>
            <Input
              value={newName}
              onChange={(e) => setNewName(e.target.value)}
              placeholder={`请输入${renamingItem?.type === 'folder' ? '文件夹' : '文档'}新名称`}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  handleRename();
                }
              }}
              autoFocus
            />
          </div>
          <div className="flex justify-end space-x-2">
            <Button variant="outline" onClick={() => {
              setShowRenameModal(false);
              setRenamingItem(null);
              setNewName('');
            }} disabled={renameLoading}>
              取消
            </Button>
            <Button variant="primary" onClick={handleRename} disabled={renameLoading || !newName.trim()}>
              {renameLoading ? '重命名中...' : '确定'}
            </Button>
          </div>
        </div>
      </Modal>

      {/* 移动弹窗 */}
      <Modal
        open={showMoveModal}
        onCancel={() => {
          setShowMoveModal(false);
          setMovingItem(null);
          setTargetFolderId(null);
        }}
        title={`移动${movingItem?.type === 'folder' ? '文件夹' : '文档'}`}
        footer={null}
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-2">目标位置</label>
            <Select
              value={targetFolderId}
              onChange={(value) => setTargetFolderId(value)}
              placeholder="选择目标文件夹"
              style={{ width: '100%' }}
              options={folderSelectData}
              showSearch
              filterOption={(input, option) => {
                if (!option || !option.label) return false;
                return String(option.label).toLowerCase().includes(input.toLowerCase());
              }}
            />
          </div>
          <div className="flex justify-end space-x-2">
            <Button variant="outline" onClick={() => {
              setShowMoveModal(false);
              setMovingItem(null);
              setTargetFolderId(null);
            }} disabled={moveLoading}>
              取消
            </Button>
            <Button variant="primary" onClick={handleMove} disabled={moveLoading || targetFolderId === null || targetFolderId === undefined}>
              {moveLoading ? '移动中...' : '确定'}
            </Button>
          </div>
        </div>
      </Modal>
      
      {/* 批量操作模态框 */}
      <Modal
        open={showBatchRenameModal}
        onCancel={() => setShowBatchRenameModal(false)}
        title="批量重命名"
        footer={null}
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-2">命名前缀</label>
            <Input 
              value={batchRenamePrefix}
              onChange={(e) => setBatchRenamePrefix(e.target.value)}
              placeholder="例如: 文档"
            />
          </div>
          <div>
            <label className="block text-sm font-medium mb-2">起始编号</label>
            <Input 
              type="number"
              value={batchRenameStartNumber}
              onChange={(e) => setBatchRenameStartNumber(parseInt(e.target.value) || 1)}
              placeholder="起始编号"
              min={1}
            />
          </div>
          <div className="flex justify-end space-x-2">
            <Button variant="outline" onClick={() => setShowBatchRenameModal(false)}>
              取消
            </Button>
            <Button variant="primary" onClick={handleBatchRename} disabled={!batchRenamePrefix.trim()}>
              确定
            </Button>
          </div>
        </div>
      </Modal>
      
      <Modal
        open={showBatchTagModal}
        onCancel={() => setShowBatchTagModal(false)}
        title="批量添加标签"
        footer={null}
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-2">选择标签</label>
            <Select
              mode="multiple"
              value={batchSelectedTags}
              onChange={setBatchSelectedTags}
              placeholder="选择要添加的标签"
              style={{ width: '100%' }}
              options={allTags.map(tag => ({ label: tag.name, value: tag.id }))}
            />
          </div>
          <div className="flex justify-end space-x-2">
            <Button variant="outline" onClick={() => setShowBatchTagModal(false)}>
              取消
            </Button>
            <Button variant="primary" onClick={handleBatchTag} disabled={batchSelectedTags.length === 0}>
              确定
            </Button>
          </div>
        </div>
      </Modal>
      
      <Modal
        open={showShareModal}
        onCancel={() => setShowShareModal(false)}
        title="文档分享"
        footer={null}
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-2">分享权限</label>
            <Radio.Group 
              value={shareConfig.permissions}
              onChange={(e) => setShareConfig({...shareConfig, permissions: e.target.value})}
            >
              <Radio value="view">仅查看</Radio>
              <Radio value="edit">可编辑</Radio>
            </Radio.Group>
          </div>
          <div>
            <label className="block text-sm font-medium mb-2">有效期</label>
            <Select
              value={shareConfig.expireDays}
              onChange={(value) => setShareConfig({...shareConfig, expireDays: value})}
              style={{ width: '100%' }}
            >
              <Select.Option value={7}>7天</Select.Option>
              <Select.Option value={30}>30天</Select.Option>
              <Select.Option value={90}>90天</Select.Option>
              <Select.Option value={0}>永久有效</Select.Option>
            </Select>
          </div>
          <div className="flex justify-end space-x-2">
            <Button variant="outline" onClick={() => setShowShareModal(false)}>取消</Button>
            <Button variant="primary" onClick={handleShareDocument}>生成分享链接</Button>
          </div>
        </div>
      </Modal>
      
      {/* 批量上传弹窗 */}
      <Modal
        open={showUploadModal}
        onCancel={() => {
          setShowUploadModal(false);
          setFileList([]);
        }}
        title="批量上传文件"
        footer={null}
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-2">选择文件</label>
            <input
              type="file"
              multiple
              onChange={(e) => {
                const files = Array.from(e.target.files || []);
                setFileList(files.map((file, index) => ({
                  uid: String(index),
                  name: file.name,
                  status: 'ready' as const,
                  originFileObj: file
                })));
              }}
              className="w-full"
            />
          </div>
          {fileList.length > 0 && (
            <div className="space-y-2">
              <div className="text-sm font-medium">已选择 {fileList.length} 个文件：</div>
              <div className="max-h-40 overflow-y-auto space-y-1">
                {fileList.map((file) => (
                  <div key={file.uid} className="text-sm text-gray-600">
                    {file.name}
                  </div>
                ))}
              </div>
            </div>
          )}
          <div className="flex justify-end space-x-2">
            <Button variant="outline" onClick={() => {
              setShowUploadModal(false);
              setFileList([]);
            }}>
              取消
            </Button>
            <Button 
              variant="primary" 
              onClick={() => {
                const files = fileList.map(f => f.originFileObj).filter(Boolean) as File[];
                handleUpload(files);
              }}
              disabled={fileList.length === 0}
            >
              上传
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default DocumentList;